<?php

use C\Config_Wt;
use I\App;
use I\DB;
use I\Proxy;
use I\Table;
use M\Middle_Public;

include '../console/feishutip.php';

class Controller extends Middle_Public {
    public function index() {
        return $this->formatlist([]);
    }

    public function ido() {
        return $this->formatlist(['leader' => $this->authed->id]);
    }

    public function icommit() {
        return $this->formatlist(['author' => $this->authed->id]);
    }

    public function itest() {
        return $this->formatlist(['tester' => $this->authed->id]);
    }

    public function iqa() {
        return $this->formatlist(['qa' => $this->authed->id]);
    }

    private function getSortedusers() {
        return DB::keyBy("select id, name, department, team from users order by team");
        $sortusers = array();
        foreach ($users as $k => $v) {
            $sortusers[$k] = iconv('UTF-8', 'GBK', $v->name);
        }
        asort($sortusers);
        $sortedusers = array();
        foreach ($sortusers as $k => $name) {
            $sortedusers[$k] = $users[$k];
        }
        return $sortedusers;
    }

    private function formatlist($searchargs) {
        $db  = DB::write();
        $ids = getgpc('ids');
        if ($ids) {
            $updates  = array();
            $changeto = getgpc('changeto');
            if ($changeto) {
                if (isset($changeto['deadline'])) {
                    $deadline = trim($row['deadline']);
                    if ($deadline == '') {
                        unset($changeto['deadline']);
                    } else {
                        //以天为单位
                        $changeto['deadline'] = strtotime($deadline) + 86400 - 1;
                    }
                }
                if (isset($changeto['ks']) && $changeto['ks']) {
                    $changeto['ks'] = strtotime($changeto['ks']);
                }
                foreach ($changeto as $key => $value) {
                    if ($value > 0) {
                        $updates[$key] = $value;
                    }
                }
            }

            if (isset($updates['tag'])) {
                $tag            = $this->get_tag($updates['tag']);
                $updates['pro'] = $tag->pro;
            }
            if (isset($updates['leader'])) {
                // if ($updates['leader'] == 106) {
                //     $updates['leader'] = 151;
                // }
                $leader                = $this->get_user($updates['leader']);
                $updates['department'] = $leader->department;
            }

            if ($updates) {
                $ids_s                 = implode(',', $ids);
                $updates['updated_at'] = date('Y-m-d H:i:s');

                $changed_tasks = $db->query('select * from tasks where id in (' . $ids_s . ')');
                foreach ($changed_tasks as $key => $value) {
                    $this->addlog($value, $updates);
                }
                $db->update('tasks')->cols($updates)->where('ID in(' . $ids_s . ')')->query();

                //凯允定制
                if (isset($updates['status']) && $updates['status'] == 10) {
                    $db->query('update tasks set bad = bad + 1 where id in (' . $ids_s . ')');
                }
            }
        }

        $options = array();
        $search  = getgpc('search');
        if (!$search) {
            $search = array();
        }

        $search  = array_merge($search, $searchargs);
        $orderby = getgpc('orderby', '');

        $where = array();

        if ($orderby == 'deadline') {
            unset($search['status']);
            $where[] = 'status<30';
        }

        if ($orderby == 'congbao') {
            $where[] = 'deadline != 0';
            $where[] = 'status<30';
        }

        foreach ($search as $key => $value) {
            if ($value > 0) {
                $options[$key] = $value;
                $where[]       = $key . '="' . addslashes($value) . '"';
            }
        }

        $title = getgpc('title');
        if ($title) {
            $options['title'] = $title;
            $where[]          = 'title like "%' . addslashes($title) . '%"';
        }

        $ismain = getgpc('ismain', 0);
        if ($ismain) {
            $where[] = 'related=0';
        }

        $sqlcount = 'select count(*) as num from tasks';
        $sql      = 'select * from tasks';
        if (count($where)) {
            $wheresql = implode(' and ', $where);
            $sqlcount .= ' where ' . $wheresql;
            $sql .= ' where ' . $wheresql;
        }

        $count_row = $db->row($sqlcount);
        $totalnum  = $count_row->num;
        $curpage   = getgpc('page', 1);
        $perpage   = 20;
        $offset    = page_get_start($curpage, $perpage, $totalnum);

        //葱爆排序到期时间优先级最高
        if ($orderby == 'congbao') {
            $sql .= ' order by deadline, status';
        } else {
            $sql .= ' order by status';
        }

        $sql .= ', priority desc';
        $sql .= ', tag desc';
        $sql .= ', level';

        if ($orderby and $orderby != 'congbao') {
            $sql .= ', ' . $orderby;
        } else {
            $sql .= ', deadline';
            $orderby = '';
        }

        $sql .= " limit $perpage offset $offset";
        $tasks = $db->query($sql);

        $tpl = 'task-list';
        if ($this->view->isajax()) {
            $tpl = 'task-list-content';
        }

        $this->init_users();
        $this->init_catys();
        $this->init_departments();
        $this->init_pros();
        $this->init_tags();
        $this->view->addData([
            'tasks'       => $tasks,
            'pros'        => $this->pros,
            'users'       => $this->users,
            'tags'        => $this->tags,
            'status'      => App::singleton()->getconfig('worktime', 'status'),
            'prioritys'   => App::singleton()->getconfig('worktime', 'priority'),
            'catys'       => $this->catys,
            'departments' => $this->departments,
            'options'     => $options,
            'orderby'     => $orderby,
            'ismain'      => $ismain,
            'totalnum'    => $totalnum,
            'curpage'     => $curpage,
            'perpage'     => $perpage,
        ]);

        return $this->view->html($tpl);
    }

    public function copy($id) {
        $db         = DB::write();
        $lockn      = 0;
        $task       = $db->row("SELECT * FROM `tasks` WHERE id='$id'");
        $related_id = $task->related;

        if ($related_id) {
            $related = $db->row("SELECT * FROM `tasks` WHERE id='$related_id'");
        } else {
            $related = clone $task;
        }

        $task->id      = 0;
        $task->status  = 12;
        $task->title   = '【请修改标题】' . $task->title;
        $task->content = $task->content;

        $this->init_users();
        $this->init_catys();
        $this->init_departments();
        $this->init_pros();
        $this->init_tags();
        return $this->view->html('task-commit', [
            'lockn'       => $lockn,
            'task'        => $task,
            'related'     => $related,
            'pros'        => $this->pros,
            'users'       => $this->users,
            'tags'        => $this->tags,
            'status'      => App::singleton()->getconfig('worktime', 'status'),
            'catys'       => $this->catys,
            'departments' => $this->departments,
        ]);
    }

    public function create($id = 0, $related_id = 0) {
        $db    = DB::write();
        $lockn = 0;
        if ($id) {
            $task       = $db->row("SELECT * FROM `tasks` WHERE id='$id'");
            $related_id = $task->related;

            $is_edit = getgpc('is_edit');
            if ($is_edit) {
                if ($task->lockc) {
                    return $this->view->error('内容已经锁定，找负责人解锁');
                }
            }

            $redis = Proxy::singleton()->getRedis();
            $lockn = $redis->get('task/' . $task->id);
        } else {
            $task = null;
        }

        if ($related_id) {
            $related = $db->row("SELECT * FROM `tasks` WHERE id='$related_id'");
        } else {
            $related = null;
        }

        $this->init_users();
        $this->init_catys();
        $this->init_departments();
        $this->init_pros();
        $this->init_tags();
        return $this->view->html('task-commit', [
            'lockn'       => $lockn,
            'task'        => $task,
            'related'     => $related,
            'pros'        => $this->pros,
            'users'       => $this->users,
            'tags'        => $this->tags,
            'status'      => App::singleton()->getconfig('worktime', 'status'),
            'catys'       => $this->catys,
            'departments' => $this->departments,
        ]);
    }

    public function lockcontent() {
        $id = getgpc('id');
        $db = DB::write();

        $task = DB::find('tasks', $id);

        if ($task->lockc) {
            if ($task->lockc != $this->authed->id) {
                return $this->view->alert('只有锁定人可以解锁');
            }
        } else {
            if ($task->leader != $this->authed->id) {
                return $this->view->alert('只有负责人可以操作');
            }
        }

        $db->update('tasks')->cols(['lockc' => $task->lockc ? 0 : $this->authed->id])->where('id=' . $id)->query();

        $t_lockc = $task->lockc ? '已开放' : '已锁定';
        $this->view->jsstr('$("#t_lockc").html("' . $t_lockc . '");');

        return $this->view->alert($task->lockc ? '成功解锁' : '成功锁定内容');
    }

    private $nametags;

    public function importexcel(Type $var = null) {
        require_once ROOT_DIR . '/vendor/excel/PHPExcel/IOFactory.php';
        //加载excel文件
        $filename          = ROOT_DIR . '/vendor/excel/result.xlsx';
        $savefilename      = ROOT_DIR . '/vendor/excel/finalresult.xlsx';
        $objPHPExcelReader = PHPExcel_IOFactory::load($filename);
        $reader            = $objPHPExcelReader->getWorksheetIterator();
        $count             = 0;
        $dbusers           = DB::all('users');
        $this->taskusers   = [];
        foreach ($dbusers as $dbuser) {
            $this->taskusers[explode('(', $dbuser->name)[0]] = $dbuser->id;
        }
        $objWriter      = new PHPExcel_Writer_Excel2007($objPHPExcelReader);
        $this->nametags = [];
        $this->init_tags();
        foreach ($this->tags as $k => $value) {
            $this->nametags[$value->name] = $k;
        }
        //循环读取sheet
        foreach ($reader as $sheet) {
            if ($sheet->getTitle() != "任务清单") {
                continue;
            }

            //读取表内容
            $content = $sheet->getRowIterator();
            //逐行处理
            $res_arr = array();
            foreach ($content as $key => $items) {
                $rows    = $items->getRowIndex(); //行
                $columns = $items->getCellIterator(); //列
                $row_arr = array();
                //确定从哪一行开始读取
                if ($rows < 4) {
                    continue;
                }

                $arow = [];
                //逐列读取
                foreach ($columns as $head => $cell) {
                    if ($cell->getColumn() == "A"
                        || $cell->getColumn() == "B"
                        || $cell->getColumn() == "C"
                        || $cell->getColumn() == "D"
                    ) {
                        continue;
                    }

                    //获取cell中数据
                    $data                     = $cell->getValue();
                    $arow[$cell->getColumn()] = $data;
                    $row_arr[]                = $data;
                }
                if ($arow["G"] == "") {
                    continue;
                }
                if ($arow["J"] != "") {
                    continue;
                }

                $count++;
                $sheet->setCellValue('J' . $rows, $this->store($arow));
            }
        }

        $objWriter->save($savefilename);
        echo '批量添加任务成功', $count;
        return $res_arr;
    }

    private function getCaty($caty) {
        if ($caty == "运营") {
            return 1000;
        }

        if ($caty == "人事") {
            return 1001;
        }

        if ($caty == "行政") {
            return 1002;
        }

        if ($caty == "技术") {
            return 1003;
        }

        if ($caty == "设计") {
            return 1005;
        }

        if ($caty == "需求") {
            return 100;
        }

        if ($caty == "改进") {
            return 101;
        }

        if ($caty == "BUG") {
            return 102;
        }

        if ($caty == "管理") {
            return 300;
        }

        if ($caty == "策划") {
            return 301;
        }

        if ($caty == "美术") {
            return 302;
        }

        if ($caty == "品控") {
            return 305;
        }

        if ($caty == "其他") {
            return 306;
        }
    }
    private function getPriority($pri) {
        if ($pri == "低") {
            return 10;
        }

        if ($pri == "中") {
            return 20;
        }

        if ($pri == "高") {
            return 99;
        }

        if ($pri == "急") {
            return 999;
        }
    }
    private function getStatus($pri) {
        if ($pri == "已完成") {
            return 98;
        } else {
            return 12;
        }
    }
    private function formatTime($timevalue) {
        if (strpos($timevalue, "-")) {
            return strtotime($timevalue);
        } else {
            return intval(($timevalue - 25569) * 3600 * 24);
        }
    }
    public function store($arow = null) {
        $me = $this->authed;

        if ($arow) {
            $id                = null;
            $row               = [];
            $row["title"]      = $arow["G"];
            $row["content"]    = $arow["H"];
            $row["department"] = 1000; // need transform
            $row["caty"]       = $this->getCaty($arow["Q"]);
            $row['priority']   = $this->getPriority($arow["O"]);
            $row['level']      = $arow["P"];
            $row['tag']        = 110;
            if ($arow['K'] == null) {
                return;
            }
            if ($this->taskusers[str_replace(' ', '', $arow['T'])] == null) {
                return $this->view->assertAlert('未加入users' . str_replace(' ', '', $arow['T']));
            }
            $row['tag']    = $this->nametags[$arow['K']];
            $row['status'] = $this->getStatus($arow['F']);
            $row['leader'] = $this->taskusers[str_replace(' ', '', $arow['T'])];
            $row['tester'] = $this->taskusers[str_replace(' ', '', $arow['V'])];
            if (isset($this->taskusers[$arow['W']])) {
                $row['qa'] = $this->taskusers[str_replace(' ', '', $arow['W'])];
            }

            if ($arow['E']) {
                $row['deadline'] = $this->formatTime($arow['E']);
            }
        } else {
            $id  = getgpc('id');
            $row = getgpc('row');
        }

        $db = DB::write();
        DB::beginTrans();

        $row['changer'] = $me->id;

        $task = null;

        if ($id) {
            $task = DB::find('tasks', $id);
            if (!$task) {
                return $this->view->assertAlert('ID 不存在');
            }

            $lockn     = getgpc('lockn', 0);
            $redis     = Proxy::singleton()->getRedis();
            $new_lockn = $redis->incr('task/' . $task->id); //+1

            if ($new_lockn > $lockn + 1) {
                $redis->decr('task/' . $task->id); //-1
                return $this->view->assertAlert('被人抢先一步修改，重新打开后再操作。');
            }

            $this->view->jsstr("lockn = $new_lockn ;"); //更新

            if (isset($row['ks']) && $row['ks']) {
                $row['ks'] = strtotime($row['ks']);
            } else {
                unset($row['ks']);
            }
            if (isset($row['deadline'])) {
                $deadline = trim($row['deadline']);
                if ($deadline == '') {
                    unset($row['deadline']);
                } else {
                    $row['deadline'] = strtotime($deadline) + 86400 - 1;
                }
            }

            if (isset($row['status'])) {
                if ($row['status'] == 11) {
                    if (!isset($row['ks'])) {
                        $row['ks'] = strtotime(date('Y-m-d'));
                    }
                    if (!$task->lockc) {
                        $row['lockc'] = $task->leader; //锁定
                        if ($this->view->isajax()) {
                            $t_lockc = $task->lockc ? '已开放' : '已锁定';
                            $this->view->jsstr('$("#t_lockc").html("' . $t_lockc . '");');
                        }
                    }
                } elseif ($row['status'] == 30) {
                    $row['jd'] = 100;
                } elseif ($row['status'] == 10) {
                    $row['jd'] = 80;
                }
            }

            foreach ($row as $k => $v) {
                if ($task->$k == $v) {
                    unset($row[$k]);
                }
            }

            if (empty($row)) {
                return $this->view->assertAlert('没有修改什么。不做保存。');
            }

            //测试状态
            if ($task->status == 50 || $task->status == 51) {
                if (isset($row['content'])) {
                    return $this->view->assertAlert('正在测试，不要修改内容。如果一定要修改，请协调后再改。');
                }

                if (isset($row['status'])) {
                    if ($row['status'] < 50 && $row['status'] != 10) {
                        return $this->view->assertAlert('正在测试中，不能修改成此状态。如果是有BUG，请修改成 《未通过》');
                    }
                }
            }

            //凯允定制
            if (isset($row['status']) && $row['status'] == 10) {
                $row['bad'] = $task->bad + 1;
            }
        } else {
            $row['author'] = $me->id;
            //BUG默认2天内解决
            if ($row['caty'] == 102) {
                $row['qa'] = $this->authed->id;
            }

            if (!$row['level']) {
                return $this->view->assertAlert('必须设定优先级等级');
            }
        }

        $now               = date('Y-m-d H:i:s');
        $row['updated_at'] = $now;

        if (isset($row['content'])) {
            $row['content'] = removehost($row['content']);
        }

        if ($this->is_tag_lock($row, $task)) {
            return $this->view->assertAlert('本版本已经被锁住。@杨凯允');
        }

        $this->onChange($row);

        if ($id) {
            $this->addlog($task, $row);
            $db->update('tasks')->cols($row)->where('id=' . $id)->query();
        } else {
            if (!isset($row['tag'])) {
                return $this->view->assertAlert('版本设置有问题');
            }
            $row['created_at'] = $now;
            $id                = $db->insert('tasks')->cols($row)->query();
            $row['id'] = $id;

            M\Middle_Feishu::singleton()->newtask((object)$row);
        }

        DB::commitTrans();
        if ($this->view->isajax()) {
            $this->view->alert('修改成功');
        } else if (!$arow) {
            $this->view->redirect('/task/show/' . $id);
        } else {
            return $id;
        }
    }

    private function is_tag_lock($row, $task) {
        if (!isset($row['tag'])) {
            return false;
        }

        if (isset($row['caty']) && $row['caty'] == 102) {
            return false;
        }

        if ($task && $task->caty == 102) {
            return false;
        }

        $tag_id = $row['tag'];
        $db     = DB::write();
        $tag    = $db->row("select * from tags where id = $tag_id");
        return $tag->lock;
    }

    private $catys = null;
    private function init_catys() {
        if (!$this->catys) {
            $this->catys = DB::keyBy("select * from titles where caty = " . App::singleton()->getconfig('worktime', 'caty'));
        }
    }

    private function get_caty($id) {
        $this->init_catys();
        return $this->catys[$id];
    }

    private $tags = null;
    private function init_tags() {
        if (!$this->tags) {
            $this->tags = DB::keyBy('select id, name, pro, `lock` from tags');
        }
    }
    private function get_tag($id) {
        $this->init_tags();
        return $this->tags[$id];
    }

    private $pros = null;
    private function init_pros() {
        if (!$this->pros) {
            $this->pros = DB::keyBy('select * from pros');
        }
    }
    private function get_pro($id) {
        $this->init_pros();
        return $this->pros[$id];
    }

    private $departments = null;
    private function init_departments() {
        if (!$this->departments) {
            $this->departments = DB::keyBy('select * from titles where caty = ' . App::singleton()->getconfig('worktime', 'department') . ' order by r ');
        }
    }

    private function get_department($id) {
        $this->init_departments();
        return $this->departments[$id];
    }

    private $users = null;
    private function init_users() {
        if (!$this->users) {
            $this->users = DB::keyBy("select id, name, department, account,team from users order by team, id");
        }
    }

    private function get_user($id) {
        $this->init_users();
        return $this->users[$id];
    }

    private function get_feishu($id) {
        $this->init_users();
        $feishu = $this->users[$id]->account;
        return $feishu;
    }

    private function addlog($old, $update) {
        $messages = '';
        $monitor  = array(
            'title', 'content', 'caty',
            'priority', 'department', 'status',
            'tag', 'pro', 'deadline',
            'changer', 'leader', 'tester', 'level',
        );
        $changed = array();
        foreach ($monitor as $col) {
            if (isset($update[$col]) && $update[$col] != $old->$col) {
                $changed[$col] = $old->$col;
            }
        }

        if (empty($changed)) {
            return;
        }

        if (isset($changed['pro'])) {
            $row            = $this->get_pro($changed['pro']);
            $changed['pro'] = $row->name;
        }

        if (isset($changed['tag'])) {
            $row            = $this->get_tag($changed['tag']);
            $changed['tag'] = $row->name;
        }

        if (isset($changed['caty'])) {
            $row             = $this->get_caty($changed['caty']);
            $changed['caty'] = $row->name;
        }

        if (isset($changed['department'])) {
            $row                   = $this->get_department($changed['department']);
            $changed['department'] = $row->name;
        }

        if (isset($changed['priority'])) {
            $prioritys           = App::singleton()->getconfig('worktime', 'priority');
            $changed['priority'] = $prioritys[$changed['priority']];
        }
        if (isset($changed['status'])) {
            $status            = App::singleton()->getconfig('worktime', 'status');
            $changed['status'] = $status[$changed['status']];
        }


        if (isset($changed['deadline'])) {
            $changed['deadline'] = date('Y-m-d', $changed['deadline']);
        }

        foreach (['author', 'leader', 'tester', 'changer'] as $col) {
            if (isset($changed[$col])) {
                $row           = $this->get_user($changed[$col]);
                $changed[$col] = $row->name;
            }
        }

        $changed['pid']        = $old->id;
        $changed['changer']    = $this->authed->name;
        $changed['created_at'] = $update['updated_at'];
        DB::write()->insert('tasklogs')->cols($changed)->query();

        $this->sendtowoa($old, $update, $changed);
    }

    private function sendtowoa($old, $update, $changed) {
        if (isset($update['status']) && $update['status'] == 98) {
            return ;
        }

        $messages = '';
        if (isset($changed['title'])) {
            $messages .= "\n\n- 标题new: {$update['title']}";
        }

        if (isset($changed['pro'])) {
            $pro            = $this->get_pro($update['pro']);
            $messages .= "\n\n- 项目: {$changed['pro']} -> {$pro->name}";
        }

        if (isset($changed['tag'])) {
            $tag            = $this->get_tag($update['tag']);
            $messages .= "\n\n- 版本: {$changed['tag']} -> {$tag->name}";
        }

        if (isset($changed['caty'])) {
            $caty             = $this->get_caty($update['caty']);
            $messages .= "\n\n- 类型: {$changed['caty']} -> {$caty->name}";
        }

        if (isset($changed['priority'])) {
            $prioritys           = App::singleton()->getconfig('worktime', 'priority');
            $priority = $prioritys[$update['priority']];
            if ($update['priority'] == 999) {
                $priority = "<font color='red'>$priority</font>";
            }
            $messages .= "\n\n- 等级: {$changed['priority']} -> {$priority}";
        }
        if (isset($changed['status'])) {
            $statuss            = App::singleton()->getconfig('worktime', 'status');
            $status = $statuss[$update['status']];
            if ($update['status'] == 10) {
                $status = "<font color='red'>$status</font>";
            }
            $messages .= "\n\n- 状态: {$changed['status']} -> {$status}";
        }

        if (isset($changed['deadline'])) {
            $deadline = date('Y-m-d', $update['deadline']);
            $messages .= "\n\n- 期限: {$changed['deadline']} -> {$deadline}";
        }

        if (isset($changed['content'])) {
            $messages .= "\n\n- 内容: 有修改，详情转到网站查看";
        }

        $oldreceive_id = $this->get_feishu($old->leader);
        $at = '';

        //当修改中有负责人或验收人时，只通知到人修改单子，不通知具体修改内容
        if (isset($changed['leader'])) {
            $newleader = $this->get_user($update['leader']);
            $receive_id    = $newleader->account;
            if ($this->authed->id == $old->leader) {//原先的负责人修改的
                $at .= "<at email=\"{$receive_id}\"></at> ";
            } elseif ($this->authed->id == $update['leader']) {
                $at .= "<at email=\"{$oldreceive_id}\"></at> ";
            } else {//其他人修改的
                $at .= "<at email=\"{$oldreceive_id}\"></at> ";
                $at .= "<at email=\"{$receive_id}\"></at> ";
            }

            $messages .= "\n\n- 负责人: {$changed['leader']} -> {$newleader->name}";

        } else {
            if ($this->authed->id != $old->leader) {
                //别人修改的要发给当前负责人
                $at .= "<at email=\"{$oldreceive_id}\"></at> ";
            }
        }

        //可测试状态
        if (isset($update['status']) && $update['status'] == 50) {
            $qa = $this->get_user(isset($update['qa']) ? $update['qa'] : $old->qa);
            $at .= "<at email=\"{$qa->account}\"></at> ";
        }

        $tag            = $this->get_tag($old->tag);

        $content = "{$at}{$this->authed->name} 修改了任务状态\n\n";
        $content .= "# [#{$old->id} &{$tag->name}& {$old->title}](http://10.77.34.52/task/show/{$old->id})";
        $content .= $messages;

        $url = 'https://docs.oa.wanmei.net/woa/api/v1/webhook/send?key=1893f3d86f044e2141a4dd80cb2f68d3';
        M\Middle_Feishu::singleton()->send($content, $url);
    }

    private function onChange(&$row) {
        if (isset($row['tag'])) {
            $tag        = $this->get_tag($row['tag']);
            $row['pro'] = $tag->pro;
        }

        if (isset($row['leader'])) {
            // if ($row['leader'] == 106) {
            //     $row['leader'] = 151;
            // }
            $leader            = DB::find('users', $row['leader']);
            $row['department'] = $leader->department;
        }
    }

    public function show($id) {
        $db   = DB::write();
        $task = $db->row('select * from tasks where id=' . $id);
        if (!$task) {
            return $this->redirect('/index/index');
        }

        $relatedsql = sprintf('select * from tasks where related = %s order by r desc limit 100', $task->related ? $task->related : $id);

        $parent_task = null;
        if ($task->related) {
            $parent_task = $db->row('select * from tasks where id=' . $task->related);
            if (!$parent_task) {
                $task->related = 0;
                Table::singleton('tasks')->update($task->id, ['related' => 0]);
            }
        }

        $redis = Proxy::singleton()->getRedis();
        $lockn = $redis->get('task/' . $task->id);

        $this->init_users();
        $this->init_catys();
        $this->init_departments();
        $this->init_pros();
        $this->init_tags();
        $this->view->addData([
            'lockn'       => $lockn ? $lockn : 0,
            'task'        => $task,
            'parent_task' => $parent_task,
            'tasks'       => $db->query($relatedsql),
            'feedbacks'   => $db->query("select * from feedbacks where pid=$id limit 10"),
            'users'       => $this->users,
            'prioritys'   => App::singleton()->getconfig('worktime', 'priority'),
            'tags'        => $this->tags,
            'pros'        => $this->pros,
            'catys'       => $this->catys,
            'departments' => $this->departments,
        ]);

        return $this->view->html('task-show', [
            'logs' => $db->query("select * from tasklogs where pid=$id order by created_at desc limit 5"),
        ]);
    }

    public function related() {
        $db = DB::write();

        $related = getgpc('related', 0); //子任务
        $id      = getgpc('id', 0); //主任务

        if (!$related) {
            $this->view->assertAlert('输入错误');
        }
        if ($related == $id) {
            $this->view->assertAlert('自己不能关联自己');
        }

        $child = $db->row('select * from tasks where id=' . $related);
        if (!$child) {
            $this->view->assertAlert('子任务不存在');
        }
        $is_main = $db->row('select * from tasks where related=' . $related . ' limit 1');
        if ($is_main) {
            $this->view->assertAlert('子任务现在是主任务');
        }

        $udata = [
            'related' => $id,
            'r'       => 0,
        ];
        $db->update('tasks')->cols($udata)->where('id=' . $related)->query();

        $this->view->redirect('/task/show/' . $id);
    }

    public function content($id) {
        echo (DB::find('tasks', $id)->content);
        exit();
    }

    public function upload() {
        $a = array('err' => 'do not recive file.');

        if (!isset($_FILES['file'])) {
            echo json_encode($a);exit();
        }

        $filedir = '/' . date('Ym');
        $homedir = Config_Wt::uploaddir;

        $uploaddir = $homedir . $filedir;
        if (!is_dir($uploaddir)) {
            @mkdir($uploaddir);
        }

        $file = $_FILES['file'];

        if (0 == $file['size']) {
            echo json_encode($a);exit();
        }

        $filename   = time() . '_' . rand(10000, 99999);
        $uploadfile = $uploaddir . '/' . $filename;
        if (!file_exists($uploadfile)) {
            @move_uploaded_file($file['tmp_name'], $uploadfile);
        }

        $a['path'] = Config_Wt::imgpath . $filedir . '/' . $filename;

        echo json_encode($a);exit();
    }

    public function diff($table, $oldid, $newid, $islog = 0) {

        if ($islog) {
            $old = DB::find($table . 'logs', $oldid);
            $new = DB::find($table . 'logs', $newid);
        } else {
            $old = DB::find($table . 'logs', $oldid);
            $new = DB::find($table . 's', $newid);
        }

        if ('task' == $table) {
            $diff = new I\HtmlDiff($old->content, $new->content);
        } else {
            $diff = new I\HtmlDiff($old->message, $new->message);
        }
        $diff->build();
        // echo "<h2>Old html</h2>";
        // echo $diff->getOldHtml();
        // echo "<h2>New html</h2>";
        // echo $diff->getNewHtml();
        // echo "<h2>Compared html</h2>";
        // echo $diff->getDifference();

        echo $diff->getDifference();exit();
    }

    public function sql() {
        $content = getgpc('c');
        if (!$content) {
            return $this->view->html('sql');
        }

        $db   = DB::write();
        $list = $db->query($content);
        $this->view->addData([
            'tasks'       => $list,
            'pros'        => DB::keyBy("select * from pros"),
            'users'       => $this->getSortedusers(),
            'tags'        => DB::keyBy("select id, name, pro from tags order by id desc"),
            'status'      => App::singleton()->getconfig('worktime', 'status'),
            'prioritys'   => App::singleton()->getconfig('worktime', 'priority'),
            'catys'       => DB::keyBy("select * from titles where caty = " . App::singleton()->getconfig('worktime', 'caty')),
            'departments' => DB::keyBy("select * from titles where caty = " . App::singleton()->getconfig('worktime', 'department')),
        ]);

        return $this->view->html('sql-content');
    }

    public function rrr($id) {
        $db = DB::write();

        $updown = getgpc('updown');

        $a = $db->row("select * from tasks where id = $id");
        $r = $a->r;

        if ($r <= 0) {
            $this->view->assertAlert('本任务没有依赖，不需要顺序');
        }

        $related = $a->related;
        if ($related <= 0) {
            $this->view->assertAlert('不是子任务');
        }

        if ($updown == 'up') {
            $b = $db->row("select * from tasks where related=$related and r > $r order by r limit 1");
        } else {
            $b = $db->row("select * from tasks where related=$related and r < $r order by r desc limit 1");
        }
        if (!$b) {
            $this->view->ajax();
        }

        Table::singleton('tasks')->update($a->id, ['r' => $b->r]);
        Table::singleton('tasks')->update($b->id, ['r' => $a->r]);

        $this->view->ajax();
    }

    //去掉依赖
    public function no_r($id, $related) {
        Table::singleton('tasks')->update($id, ['r' => 0]);
        $this->view->redirect('/task/show/' . $related);
    }

    //加入流程，直接放到最下面
    public function add_r($id) {
        $db      = DB::write();
        $task    = $db->row("select * from tasks where id = $id");
        $related = $task->related;
        if ($related <= 0) {
            $this->view->assertAlert('不是子任务');
        }

        $row  = $db->row('select min(r) as r from tasks where r > 0 and related = ' . $related);
        $minr = ($row && $row->r > 0) ? $row->r - 1 : 1000;

        Table::singleton('tasks')->update($id, ['r' => $minr]);
        $this->view->redirect('/task/show/' . $task->related);
    }
}
